package org.example.myleet.p856;

import java.util.Deque;
import java.util.LinkedList;

public class Solution {
    public int scoreOfParentheses(String s) {
        Deque<Character> stack = new LinkedList<>();
        int totalScore = 0;
        int idx = 0;
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(c);
            } else {
                stack.pop();
            }
            if (stack.isEmpty()) {
                totalScore += scoreOfRoundParentheses(s.substring(idx, i + 1));
                idx = i + 1;
            }
        }
        return totalScore;
    }

    private int scoreOfRoundParentheses(String s) {
        if ("()".equals(s)) {
            return 1;
        }
        if (s.charAt(1) == '(') {
            return 2 * scoreOfParentheses(s.substring(1, s.length() - 1));
        }
        return 1 + scoreOfRoundParentheses(s.substring(2));
    }
}
